#!/usr/bin/python
# pip install -U cos-python-sdk-v5
import urllib.parse
from commons.storage.base import BaseStorage
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client


class CosOss(BaseStorage):

    def setup(self, key_id=None, secret=None, region=None, bucket=None, root_dir='hss', client=None,
              cdn=None, host=None):
        config = CosConfig(SecretId=key_id, SecretKey=secret, Region=region)
        self.client = CosS3Client(config)
        self.bucket = bucket
        host = host.split('://', 1)[-1]
        self.host = cdn if cdn else f'https://{bucket}.{host}/'
        self.root = root_dir.strip('/')

    def object_exists(self, path: str) -> bool:
        path = self.parse_path(path)
        exist = self.client.object_exists(self.bucket, path)
        return exist

    def parse_path(self, path):
        if path.startswith('/'):
            return f'{self.root}{path}'
        else:
            return f'{self.root}/{path}'

    def upload(self, path, data, mode=BaseStorage.Write, expire: int = None):
        """
        @params path: 上传到云端的文件名
        @params data: 上传数据，需要二进制
        @params mode: 写模式 Write/Append
        @params expire: 过期时间单位 s
        """
        path = self.parse_path(path)
        if mode == BaseStorage.Append:
            result = self.client.head_object(self.bucket, path)
            self.client.append_object(self.bucket, path, result.get("Content-Length"), data)
        else:
            self.client.put_object(self.bucket, data, path)

    def download_url(self, file_path):
        """
        @params path: 上传到云端的文件名
        """
        # return self.client.get_object_url(self.bucket,file_path)

        return self.host + urllib.parse.quote(self.parse_path(file_path))

    def delete(self, path):
        path = self.parse_path(path)
        self.bucket.delete_object(self.bucket, path)

    def get_file_meta(self, path):
        """
        获取文件元信息
        :param path:
        :return: head.last_modified, head.content_type, head.content_length

        head.last_modified: 文件最后修改时间戳，类型为int，可能是None
        head.content_type: 文件的MIME类型，可能是None
        head.content_length(bytes): Content-Length，可能是None
        """
        path = self.parse_path(path)
        result = self.client.head_object(self.bucket, path)
        return result['Last-Modified'], result['Content-Type'], result['Content-Length']

    def list_dir_files(self, path: str, max_keys=100) -> list:
        """
        获取目录下的所有文件
        """
        keys = []
        for obj in self.client.list_objects(Bucket=self.bucket, prefix=path):
            if 'Contents' in obj:
                for content in obj['Contents']:
                    keys.append(content['Key'])
        return keys


if __name__ == '__main__':
    def demo():
        # secret_id = 'AKIDwf8uQfcIgndCTTBcmfHfma7NLLIzPFtH'  # 替换为用户的 secretId
        # secret_key = 'B5h38vQdZFCsHTP4EDwPdbKnzuZx5wXr'  # 替换为用户的 secretKey
        # region = 'ap-nanjing'  # 替换为用户的 Region
        # bucket = 'szhss-1313454947'
        # config = {"key_id": "AKIDwf8uQfcIgndCTTBcmfHfma7NLLIzPFtH",
        #           "secret": "B5h38vQdZFCsHTP4EDwPdbKnzuZx5wXr",
        #           "bucket": "szhss-1313454947",  # 桶名
        #           "region": "ap-nanjing",
        #           "host": "cos.ap-nanjing.myqcloud.com"
        #           }
        config = {"key_id": "AKIDpWyBsPnxsZ1DrHZeYJqAG7i6F9mCNJ9k",
                  "secret": "OXnrhHclfLoytZzCC0hDUVMzOflokU2S",
                  "bucket": "szhsz-1307613814",  # 桶名
                  "region": "ap-shanghai",
                  "host": "cos.ap-shanghai.myqcloud.com"
                  }

        oss = CosOss(**config)
        # print(oss.list_dir_files("hss"))
        path = '测试图片你好.jpg'

        with open("./测试图片.png", 'rb') as f:
            oss.upload(path, f)

        print(oss.download_url(path))


    demo()
